<template>
  <div class="certificate-page">
    <!-- 标签页导航 -->
    <el-tabs v-model="activeTab" class="custom-tabs">
      <el-tab-pane label="所有证书" name="all"></el-tab-pane>
      <el-tab-pane label="有效证书" name="valid"></el-tab-pane>
      <el-tab-pane label="过期证书" name="expired"></el-tab-pane>
      <el-tab-pane label="待发证书" name="pending"></el-tab-pane>

      <!-- 内容区域 -->
      <div class="cert-list">
        <el-card
          v-for="item in filteredCertificates"
          :key="item.id"
          class="cert-card"
        >
          <div class="card-header">
            <span class="cert-name">证书项目：{{ item.certProject }}</span>
            <span class="cert-tag" :class="getTagClass(item)">{{ getTagText(item) }}</span>
          </div>

          <!-- Flex容器包裹信息和按钮 -->
          <div class="card-content">
            <div class="cert-info">
              <div class="info-row">
                <div class="info-item">
                  <span class="label">证书类型：</span>
                  <span class="value">{{ item.certType }}</span>
                </div>
                <div class="info-item">
                  <span class="label">证书编号：</span>
                  <span class="value">{{ item.certNo }}</span>
                </div>
              </div>

              <div class="info-row">
                <div class="info-item">
                  <span class="label">发证时间：</span>
                  <span class="value">{{ item.issueTime }}</span>
                </div>
                <div class="info-item">
                  <span class="label">有效期起：</span>
                  <span class="value">{{ item.validStart }}</span>
                </div>
                <div class="info-item">
                  <span class="label">有效期止：</span>
                  <span class="value">
                    {{ item.validEnd }}
                    <!-- 已过期提示：有效期止存在 且 早于当前日期 -->
                    <span v-if="(item.validEnd && new Date(item.validEnd) < new Date())" class="expire-tip"> 证书已过期，需复审换证</span>
                    <!-- 将过期提示：满足3个月内到期（未过期） -->
                    <span v-if="item.willExpire" class="expire-tip"> 3个月内证书将过期</span>
                  </span>
                </div>
              </div>

              <div class="info-row">
                <div class="info-item">
                  <span class="label">纸质证书：</span>
                  <span class="value">{{ item.paperCert }}</span>
                </div>
                <div class="info-item" v-if="item.expressNo">
                  <span class="label">快递单号：</span>
                  <span class="value">{{ item.expressNo }}</span>
                </div>
              </div>
            </div>

            <!-- 右侧按钮区域 -->
            <div class="cert-actions">
              <el-button
                size="mini"
                class="action-btn"
                @click="viewElectronicCertificate(item)"
              >
                查看证书
              </el-button>
              <el-button
                size="mini"
                class="action-btn"
                @click="handleRenewalApply(item)"
                v-if="(item.validEnd && new Date(item.validEnd) < new Date())"
              >
                复审换证
              </el-button>
              <el-button
                size="mini"
                class="action-btn"
                @click="handleRenewalApply(item)"
                v-if="item.willExpire"
              >
                复训换证
              </el-button>
              <el-button
                size="mini"
                class="action-btn"
                @click="fastIssuePaperCertificate(item)"
              >
                申请纸质证书
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 空状态提示 -->
        <div v-if="filteredCertificates.length === 0" class="empty-state">
          <el-empty description="暂无证书数据"></el-empty>
        </div>
      </div>

      <!-- 查看电子证书弹窗 -->
      <ViewCertificateDialogVue
        :visible.sync="viewCertificateTemplateDialog"
        :template-data="viewCertificateTemplateData"
      />
      <!-- 快递发放证书弹窗 -->
      <FastIssuePaperCertificateDialog
        :visible.sync="fastIssueVisible"
        :certificate-data="FastIssueData"
        @submit="handleFastIssueSubmit"
      />
      <!-- 现场领取证书弹窗 -->
      <OnSitePickupDialog
        :visible.sync="onSitePickupVisible"
        :certificate-list="selectedCertificatesForPickup"
        @confirm="handleConfirmPickup"
      />
      <!-- 新增个人复审资料 -->
      <add-personal-review
        ref="addPersonalReview"
        :dict-data="dictData"
      ></add-personal-review>
    </el-tabs>
  </div>
</template>

<script>
import { getStudentCertificateInfo } from "@/api/training/students";
import {
  listCertificateReissue,
  getCertificateReissue,
  delCertificateReissue,
  addCertificateReissue,
  updateCertificateReissue,
} from "@/api/certificate/changeCertificate";
import {
  listCertificateIssue,
  getCertificateIssue,
  delCertificateIssue,
  addCertificateIssue,
  updateCertificateIssue,
  getElectronicInfo,
  expressPaperCertificate,
  getCertificateIssueList,
  scenePaperCertificate,
  generateElectronic,
  cancelElectronic,
} from "@/api/certificate/issue";
import { getDicts } from "@/api/system/dict/data";
import ViewCertificateDialogVue from "@/components/Certificate/issue/ViewCertificateDialog.vue";
import FastIssuePaperCertificateDialog from "@/components/Certificate/issue/FastIssuePaperCertificateDialog.vue";
import OnSitePickupDialog from "@/components/Certificate/issue/OnSitePickupDialog.vue";
import CertificateDownloader from "@/components/Certificate/issue/certificateDownloader";
import AddPersonalReview from "@/components/Certificate/reexamination/AddPersonalReview.vue";

export default {
  name: "CertificatePage",
  components: {
    ViewCertificateDialogVue,
    FastIssuePaperCertificateDialog,
    OnSitePickupDialog,
    AddPersonalReview,
  },
  data() {
    return {
      activeTab: "all",
      certificates: [],
      viewCertificateTemplateDialog: false,
      viewCertificateTemplateData: [],
      fastIssueVisible: false,
      FastIssueData: [],
      onSitePickupVisible: false,
      tempIssueData: [],
      selectedCertificatesForPickup: [],
      // 添加字典数据存储
      dictData: {
        unitNatureOptions: [],
        documentTypeOptions: [],
        nationOptions: [],
        educationOptions: [],
        administrativeAreaOptions: [],
        userTypeOptions: [],
      },
    };
  },
  computed: {
    filteredCertificates() {
      switch (this.activeTab) {
        case "valid":
          return this.certificates.filter((item) => item.status === "valid");
        case "expired":
          return this.certificates.filter((item) => item.status === "expired");
        case "pending":
          return this.certificates.filter((item) => item.status === "pending");
        default:
          return this.certificates;
      }
    },
  },
  created() {
    this.getList();
    this.loadAllDicts();
  },
  methods: {
    // 统一加载所有字典数据
    loadAllDicts() {
      const dictPromises = [
        getDicts("unit_nature"),
        getDicts("pxzx_zjlx"),
        getDicts("pub_mz"),
        getDicts("pxzx_xl"),
        getDicts("administrative_area"),
        getDicts("rylx"),
      ];

      Promise.all(dictPromises)
        .then((responses) => {
          this.dictData.unitNatureOptions = responses[0].data;
          this.dictData.documentTypeOptions = responses[1].data;
          this.dictData.nationOptions = responses[2].data;
          this.dictData.educationOptions = responses[3].data;
          this.dictData.administrativeAreaOptions = responses[4].data;
          this.dictData.userTypeOptions = responses[5].data;
        })
        .catch((error) => {
          console.error("字典数据加载失败:", error);
        });
    },
    // 报名复训换证
    handleRenewalApply() {
      this.$refs.addPersonalReview.open("add");
    },
    // 现场领取证书
    async onSitePickupCertificate(item) {
      const res = await getElectronicInfo(item.id);
      const certificates = res.data;
      if (certificates.length === 0) {
        this.$message.warning("未获取到证书信息");
        return;
      }
      this.viewCertificateTemplateData = certificates;
      this.selectedCertificatesForPickup = this.viewCertificateTemplateData.map(
        (item) => ({
          certificateIssueId: item.certificateIssueId,
          certificateNo: item.certificateIssueId,
          studentName: item.studentName,
          idNumber: item.idNumber,
          phonenumber: item.phonenumber,
          trackingNo: item.trackingNo,
        })
      );
      this.onSitePickupVisible = true;
    },
    // 确认现场领取
    handleConfirmPickup() {
      const ids = this.selectedCertificatesForPickup.map(
        (item) => item.groupId || item.certificateIssueId
      );
      // 实际业务接口调用可在此开启
      // this.$api.certificate.onSitePickupCertificates({ ids }).then(() => {
      //   this.$modal.msgSuccess("证书已标记为现场领取");
      //   this.getList();
      //   this.onSitePickupVisible = false;
      // }).catch((err) => {
      //   this.$message.error("标记失败：" + err.message);
      // });
    },
    // 快递发放证书
    async fastIssuePaperCertificate(item) {
      const res = await getElectronicInfo(item.id);
      const certificates = res.data;
      if (certificates.length === 0) {
        this.$message.warning("未获取到证书信息");
        return;
      }
      this.viewCertificateTemplateData = certificates;
      this.FastIssueData = this.viewCertificateTemplateData.map((item) => ({
        certificateIssueId: item.certificateIssueId,
        certificateNo: item.certificateIssueId,
        studentName: item.studentName,
        idNumber: item.idNumber,
        phonenumber: item.phonenumber,
        trackingNo: item.trackingNo,
      }));
      this.fastIssueVisible = true;
    },
    // 快递发放证书提交
    handleFastIssueSubmit(data) {
      expressPaperCertificate(data)
        .then(() => {
          this.$modal.msgSuccess("证书已安排快递发放");
          this.getList();
          this.fastIssueVisible = false;
        })
        .catch((err) => {
          this.$message.error("发放失败：" + err.message);
        });
    },
    // 获取证书列表（核心修正：调试打印+变量名错误）
    async getList() {
      try {
        const res = await getStudentCertificateInfo(
          this.$store.state.user.studentId
        );
        if (res.code === 200 && res.rows) {
          this.certificates = res.rows.map((originalItem) => {
            // 状态转换
            let status = "valid";
            switch (originalItem.certificateStatus) {
              case "0": status = "valid"; break;
              case "1": status = "expired"; break;
              case "2": status = "pending"; break;
              default: status = "valid";
            }
            // 纸质证书领取方式转换
            let paperCert = "未申请";
            if (originalItem.receiveMethod === "1") paperCert = "现场";
            else if (originalItem.receiveMethod === "2") paperCert = "快递";
            // 证书类型映射
            let certType = "";
            switch (originalItem.certificateType) {
              case "1": certType = "新训"; break;
              case "2": certType = "换证"; break;
              case "3": certType = "新训/换证"; break;
              default: certType = originalItem.certificateType || "";
            }
            // 日期格式化工具
            const formatDate = (date) => date || "";
            // 处理后的有效期止（避免变量名混淆）
            const processedValidEnd = formatDate(originalItem.validityEnd);
            // 生成唯一ID
            const uniqueId = originalItem.certificateNo || `cert_${Math.random().toString(36).slice(2, 11)}`;

            const isExpired = processedValidEnd !== "" && new Date(processedValidEnd) < new Date();

            return {
              id: uniqueId,
              certProject: originalItem.projectName || "",
              certType: certType,
              certNo: originalItem.certificateNo || "",
              issueTime: formatDate(originalItem.digitalIssueTime),
              validStart: formatDate(originalItem.validityStart),
              validEnd: processedValidEnd, // 赋值处理后的有效期止
              paperCert: paperCert,
              expressNo: originalItem.trackingNo || "",
              status: status,
              willExpire: this.calculateWillExpire(originalItem.validityEnd),
              item: originalItem,
            };
          });
        }
      } catch (error) {
        console.error('获取证书列表失败：', error);
        this.certificates = [];
      }
    },
    // 计算是否3个月内过期
    calculateWillExpire(validEnd) {
      if (!validEnd) return false;
      const now = new Date();
      const endDate = new Date(validEnd);
      if (endDate < now) return false;
      const remainingMonths = (endDate.getFullYear() - now.getFullYear()) * 12 + (endDate.getMonth() - now.getMonth());
      return remainingMonths <= 3;
    },
    // 获取标签样式类
    getTagClass(item) {
      if (item.status === "valid") {
        return item.willExpire ? "tag-will-expire" : "tag-valid";
      } else if (item.status === "expired") {
        return "tag-expired";
      } else if (item.status === "pending") {
        return "tag-pending";
      }
      return "";
    },
    // 获取标签文本
    getTagText(item) {
      if (item.status === "valid") {
        return item.willExpire ? "将过期" : "有效";
      } else if (item.status === "expired") {
        return "过期";
      } else if (item.status === "pending") {
        return "待发";
      }
      return "";
    },
    // 查看电子证书
    viewElectronicCertificate(item) {
      getElectronicInfo(item.id)
        .then((res) => {
          const certificates = res.data || [];
          if (certificates.length === 0) {
            this.$message.warning("未获取到证书信息");
            return;
          }
          this.viewCertificateTemplateData = certificates;
          this.$nextTick(() => {
            this.viewCertificateTemplateDialog = true;
          });
        })
        .catch((err) => {
          this.$message.error("获取证书失败：" + err.message);
        });
    },
    // 下载电子证书
    async downloadElectronicCertificate(item) {
      try {
        const res = await getElectronicInfo(item.id);
        const certificates = res.data || [];
        await CertificateDownloader.downloadCertificates(certificates);
        this.$message.success("证书下载成功");
      } catch (error) {
        this.$message.error("下载失败：" + error.message);
      }
    },
  },
};
</script>

<style scoped>
.certificate-page {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.custom-tabs {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

::v-deep .el-tabs__header {
  margin-bottom: 20px;
}

::v-deep .el-tabs__item {
  font-size: 14px;
  color: #6b7280;
  padding: 0 16px;
}

::v-deep .el-tabs__item.is-active {
  color: #165dff;
  font-weight: 500;
}

::v-deep .el-tabs__active-bar {
  background-color: #165dff;
  height: 2px;
}

.cert-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cert-card {
  border: none;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
}

.cert-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f9fafb;
  border-bottom: 1px solid #f0f2f5;
}

.cert-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2329;
}

.cert-tag {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.tag-valid {
  background-color: #e6f7ee;
  color: #00b42a;
}

.tag-will-expire {
  background-color: #fff1f0;
  color: #f53f3f;
}

.tag-expired {
  background-color: #f2f3f5;
  color: #86909c;
}

.tag-pending {
  background-color: #e6f7ff;
  color: #165dff;
}

/* 卡片内容区Flex布局 - 固定按钮区不被挤压 */
.card-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px 20px;
  gap: 20px;
}

.cert-info {
  flex: 1; /* 信息区占满剩余空间 */
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 32px;
  margin-bottom: 12px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  display: flex;
  align-items: center;
  min-width: 220px;
}

.label {
  font-size: 14px;
  color: #6b7280;
  margin-right: 8px;
  white-space: nowrap;
}

.value {
  font-size: 14px;
  color: #1f2329;
  line-height: 1.5;
}

.expire-tip {
  color: #f53f3f;
  margin-left: 4px;
}

/* 按钮区固定宽度+禁止收缩+统一对齐 */
.cert-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 120px;
  flex-shrink: 0;
  align-items: flex-end;
}

/* 统一按钮样式：固定宽度+文字居中 */
.action-btn {
  width: 100px;
  padding: 5px 0;
  color: #165dff;
  justify-content: center;
}

::v-deep .action-btn .el-button__text {
  padding: 0 8px;
}

.empty-state {
  padding: 48px 0;
  text-align: center;
}

/* 响应式调整：小屏幕按钮区横向排列 */
@media (max-width: 768px) {
  .certificate-page {
    padding: 16px;
  }

  .card-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .cert-actions {
    flex-direction: row;
    gap: 10px;
    width: 100%;
    justify-content: flex-end;
    margin-top: 16px;
    align-items: center;
  }

  .action-btn {
    width: auto;
    padding: 5px 12px;
  }

  .info-row {
    gap: 12px 16px;
  }

  .info-item {
    min-width: 100%;
  }
}
</style>
